package com.caih.contacts.controller;


import com.caih.contacts.entity.Department;
import com.caih.contacts.entity.Result;
import com.caih.contacts.service.DepartmentService;
import com.caih.contacts.service.WeiXinDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class DeprtmentController {
    @Autowired
    private DepartmentService departmentService;
   @Autowired
   private  WeiXinDepartmentService weiXinDepartmentService;

    /**
     * 创建部门
     * @param dept
     * @return
     */
    @PostMapping("/saveDept")
    public Result<Department> save(Department dept){
        Result<Department> result = weiXinDepartmentService.createDep(weiXinDepartmentService.getAccessToken().getToken(),dept);

        if (result.getCode() == 0){
            departmentService.save(dept);
        }else{
            result.setData(null);
        }

        return result;
    }


    /**
     * 根据id删除
     * 删除有点bug
     * @param id
     * @return
     */
    @GetMapping("/deleteDept/{id}")
    public Result<String> deleteById(@PathVariable Integer id){

        //通讯录同步问题
        Result<String> result = weiXinDepartmentService.deleteDep(weiXinDepartmentService.getAccessToken().getToken(),id);
        if(result.getCode() == 0){
            departmentService.deleteById(id);
        }else{
            result.setData(null);
        }
        return result;
    }


    /**
     * 更新
     * 有些问题
     * @param dept
     * @returnt
     */
    @PutMapping("/updateDept")
    public Result<Department> update(Department dept){
        //通讯录同步
        Result<Department> result =weiXinDepartmentService.updateDep(weiXinDepartmentService.getAccessToken().getToken(),dept);
        if(result.getCode() == 0){
            departmentService.update(dept);
        }else{
            result.setData(null);
        }
        return result;
    }




    /**
     * 查询全部部门列表
     * @return
     */
    @GetMapping("/queryDeptAll")
    public Result<List<Department>> queryAll(){
    Result<List<Department>> result= departmentService.queryAll();
    return result;
}

    /**
     * 根据ID查询
     * @param id
     * @return
     */
    @GetMapping("/queyById/{id}")
    public Result<Department> queryById(@PathVariable Integer id){
     Result<Department> result =departmentService.queryById(id);
     return result;
}


    /**
     * 查父级部门
     * @param parent_id
     * @return
     */
    @GetMapping("/queryByParent_id/{parent_id}")
public Result<List<Department>> queryByParentid(@PathVariable Integer parent_id){
    Result<List<Department>> result=departmentService.queryByParentid(parent_id);
    return result;
}

}
